<template>
	<view :class="themeName">
		<view class="payment u-skeleton">
			<!-- Header -->
			<view class="payment-header">
				<price class="u-skeleton-fillet" :content="amount" mainSize="56rpx" minorSize="40rpx" color="#FFFFFF"
					:prefix="price_symbol" />
				<template v-if="timeout > 0">
					<view class="payment-count-down">
						<text>{{ $zhTran('支付剩余时间') }}</text>
						<u-count-down :timestamp="timeout" :show-days="false" :show-hours="false" :font-size="22" />
					</view>
				</template>
			</view>

			<!-- Main -->
			<view class="payment-main">
				<view class="payway-container u-skeleton-fillet">
					<!-- Payway -->
					<u-radio-group v-model="payway" style="width: 100%;">
						<view class="payway">
							<view class="payway-item" v-for="(item, index) in paywayList" :key="item.id"
								@click="changePayway(item.pay_way, item.pay_enabled)">
								<u-image :src="item.icon" width="48" height="48" mode="scaleToFill" />
								<view class="payway-item-content">
									<text class="payway-item-content-name">{{ item.name }}</text>
									<text class="payway-item-content-tips">{{ item.extra }}</text>
								</view>
								<u-radio shape="circle" :name="item.pay_way" :active-color="themeColor"
									:disabled="(order_pay_way == 5 && item.pay_way != 2) || item.pay_enabled == 2" />
							</view>
						</view>
					</u-radio-group>
					<template v-if="!paywayList.length">
						<view class="payway-empty">{{ $zhTran('暂无支付方式') }}</view>
					</template>
					<view v-if="payway == 5" style="padding: 20rpx 0;">
						<u-input v-model="groupPay_balMoney" :placeholder="$zhTran('请输入余额支付金额')" type="digit"
							:clearable="true" :border="true" class="grouppay-bal-input"></u-input>
					</view>
				</view>
			</view>

			<!-- Footer -->
			<view class="payment-footer" v-if="paywayList.length">
				<view :class="['payment-submit', 'u-skeleton-fillet', { 'payment-submit--disabled': loadingPay }]"
					@tap="queryPayResult" class="m-r-20">
					<u-loading mode="circle" :show="loadingPay" />
					<text v-show="!loadingPay">{{ $zhTran('刷新支付状态') }}</text>
				</view>
				<view :class="['payment-submit', 'u-skeleton-fillet', { 'payment-submit--disabled': loadingPay }]"
					@tap="handlePrepay">
					<u-loading mode="circle" :show="loadingPay" />
					<text v-show="!loadingPay">{{ $zhTran('立即支付') }}</text>
				</view>
			</view>
			

			<!-- 页面状态 -->
			<page-status :status="pageStatus">
				<template #error>
					<u-empty :text="pageErrorMsg" :src="$getImageUri('resource/image/shopapi/uniapp/empty/order.png')"
						:icon-size="280" />
				</template>
			</page-status>
		</view>

		<u-modal v-model="kingdeeAlipayShow" @confirm="handleCopy(kingdeeAlipayCodeUrl)"
			@cancel="handleKingdeeAlipayPay" :show-cancel-button="true" :cancel-text="$zhTran('已完成支付')"
			:confirm-text="$zhTran('复制链接')" ref="uModal" :async-close="true">
			<view class="slot-content">
				<view class="text-center p-20 line-3">
					<rich-text :nodes="kingdeeAlipayContent"></rich-text>
				</view>
			</view>
		</u-modal>

		<u-skeleton :loading="loadingSkeleton" :animation="true" bgColor="#FFFFFF" />
	</view>
</template>


<script>
	/**
	 * @description 支付页面
	 * @query {String} from 订单来源: order-商品订单; recharge-充值订单;
	 * @query {Number} order_id	订单ID
	 */
	import {
		mapGetters
	} from 'vuex'
	import {
		apiPrepay,
		apiPayway,
		apiPayStatus
	} from '@/api/app'
	import {
		wxpay,
		alipay,
		ttpay,
		tonglianpay,
		houlianpay,
		eeasypay
	} from '@/utils/pay'
	import {
		PaymentStatusEnum,
		PayWayEnum,
		PageStatusEnum,
		ClientEnum
	} from '@/utils/enum'
	import {
		apiMnpAuthPay,
	} from "@/api/user";
	import {
		getCode,
	} from "@/utils/login";
	import {
		copy,
		isWeixinClient,
	} from "@/utils/tools";
	import wechath5 from "@/utils/wechath5";

	export default {
		name: 'Payment',

		data() {
			return {
				from: '', // 订单来源
				order_id: '', // 订单ID
				amount: 0, // 支付金额
				timeout: 0, // 倒计时间戳
				payway: '', // 支付方式
				paywayList: [], // 支付方式列表

				pageStatus: PageStatusEnum['NORMAL'],
				pageErrorMsg: '',
				loadingSkeleton: true, // 骨架屏Loading
				loadingPay: false, // 支付处理中Loading 
				price_symbol: '￥',
				groupPay_balMoney: '',
				order_pay_way: 0,
				pay_appid: '',
				pay_openid: '',
				payOpenWays: [
					PayWayEnum['WECHAT'],
					PayWayEnum['WALLET_WECHAT'],
					PayWayEnum['RCB_WECHAT'],
					PayWayEnum['KINGDEE_WECHAT'],
					PayWayEnum['TONG_LIAN_PAY'],
					PayWayEnum['E_EASY_PAY'],
					PayWayEnum['HOU_LIAN_PAY'],
				],
				kingdeeAlipayShow: false,
				kingdeeAlipayCodeUrl: '',
				kingdeeAlipayContent: ''
			}
		},
		methods: {
			handleCopy: copy,
			// 更改支付方式
			changePayway(value, pay_enabled) {
				console.log('pay_enabled', pay_enabled)
				if (!(this.order_pay_way == 5 && value != 2) && pay_enabled == 1)
					this.$set(this, 'payway', value)
			},

			// 初始化页面数据
			initPageData() {
				// 获取支付方式
				return new Promise((resolve, reject) => {
					apiPayway({
						from: this.from,
						order_id: this.order_id,
					}).then(ndata => {
						let data = this.$zhTran(ndata)
						this.amount = data.order_amount
						this.order_pay_way = data.order_pay_way
						this.paywayList = data.lists
						this.price_symbol = data.price_symbol
						this.paywayList.forEach(item => {
							if (item.pay_enabled == 1) {
								this.payway = item.pay_way
								return true
							}
						})
						// this.payway = this.paywayList[0]?.pay_way
						// 倒计时
						const startTimestamp = new Date().getTime() / 1000
						const endTimestamp = data.cancel_time * 1
						this.timeout = endTimestamp - startTimestamp
						resolve(data)
					}).catch(errMsg => reject(errMsg))
				})
			},
			// 预支付处理
			async handlePrepay() {
				
				// 阻止重复操作
				if (this.loadingPay) return
				this.loadingPay = true

				var groupPay_balMoney = this.groupPay_balMoney
				console.log('groupPay_balMoney', this.groupPay_balMoney)
				if (this.payway == 5) {
					if (groupPay_balMoney == '' || groupPay_balMoney == 0)
						this.payway = 2

					if (parseFloat(groupPay_balMoney) >= parseFloat(this.amount))
						this.payway = 1
				}

				// #ifdef MP-WEIXIN
				switch (+this.payway) {
					case PayWayEnum['WECHAT']:
					case PayWayEnum['WALLET_WECHAT']:
					case PayWayEnum['RCB_WECHAT']:
					case PayWayEnum['KINGDEE_WECHAT']:
					case PayWayEnum['E_EASY_PAY']:
					case PayWayEnum['HOU_LIAN_PAY']:
						const code = await getCode();
						await apiMnpAuthPay({
							code,
						}).then((res) => {
							this.pay_openid = res.openid
						});
						break
				}
				// #endif

				if (this.payway == PayWayEnum['KINGDEE_ALIPAY']) {
					// 处理：支付
					apiPrepay({
						from: this.from,
						order_id: this.order_id,
						pay_way: this.payway,
						groupPay_balMoney: this.groupPay_balMoney == '' ? 0 : this.groupPay_balMoney,
						pay_openid: this.pay_openid
					}).then(async ({
						config,
						pay_way,
						one_year_pass,
						terminal
					}) => {
						this.kingdeeAlipayShow = true
						this.kingdeeAlipayCodeUrl = config.codeUrl
						this.kingdeeAlipayContent = "复制支付链接至浏览器打开<br>" + this.kingdeeAlipayCodeUrl
					}).finally(() => {
						this.loadingPay = false
						uni.reLaunch({
							url: `/bundle4/pages/transactres/paymentres?order_id=${this.order_id}`
						})
					})
				} else {
					// 处理：支付
					apiPrepay({
						from: this.from,
						order_id: this.order_id,
						pay_way: this.payway,
						groupPay_balMoney: this.groupPay_balMoney == '' ? 0 : this.groupPay_balMoney,
						pay_openid: this.pay_openid
					}).then(async ({
						config,
						pay_way,
						one_year_pass,
						terminal
					}) => {
						console.log('pay_way', pay_way);
						switch (+pay_way) {
							case PayWayEnum['WALLET']:
							case PayWayEnum['CASH_CREDIT']:
								await this.handleWalletPay()
								break
							case PayWayEnum['WECHAT']:
							case PayWayEnum['WALLET_WECHAT']:
							case PayWayEnum['RCB_WECHAT']:
							case PayWayEnum['KINGDEE_WECHAT']:
								await this.handleWechatPay(config)
								break
							case PayWayEnum['ALIPAY']:
								await this.handleAlipayPay(config)
								break
							case PayWayEnum['TOUTIAO']:
								await this.handleTtPay(config)
								break
							case PayWayEnum['CASH_DELIVERY']:
								await this.handlePayResult(PaymentStatusEnum['SUCCESS'])
								break
							case PayWayEnum['TONG_LIAN_PAY']:
								if (one_year_pass == 0 || terminal == ClientEnum['OA_WEIXIN']) {
									//未满一年，调用收银宝
									this.pay_appid = config.pay_appId
									await this.handleTongLianPay(config)
								} else {
									await this.handleWechatPay(config)
								}
								break
							case PayWayEnum['E_EASY_PAY']:
								if (one_year_pass == 0 || terminal == ClientEnum['OA_WEIXIN']) {
									//未满一年，调用收银宝
									this.pay_appid = config.pay_appId
									await this.handleEEasyPay(config)
								} else {
									await this.handleWechatPay(config)
								}
								break
							case PayWayEnum['HOU_LIAN_PAY']:
								this.pay_appid = config.pay_appId
								await this.handleHouLianPay(config)
								break
							default:
								throw this.$zhTran('支付异常')
						}
					}).then(() => {
						this.handlePayResult(PaymentStatusEnum['SUCCESS'])
						console.log('PaymentStatusEnum:', PaymentStatusEnum['SUCCESS'])
					}).catch(errMsg => {
						this.handlePayResult(PaymentStatusEnum['FAIL'])
						console.log('PAYMENT_ERROR_MSG:', errMsg)
					}).finally(() => {
						this.loadingPay = false
						uni.reLaunch({
							url: `/bundle4/pages/transactres/paymentres?order_id=${this.order_id}`
						})
					})
				}
			},

			// 微信支付  
			handleWechatPay(data) {
				// return new Promise((resolve, reject) => {
				// 	wxpay(data)
				// 		.then(async (res) => {
				// 			// #ifndef H5
				// 			resolve(res)
				// 			// #endif

				// 			// #ifdef H5
				// 			this.$on('h5_payment', () => {
				// 				this.queryPayResult().then(result => {
				// 					result ? resolve(res) : reject(res)
				// 				}).catch(errMsg => reject(errMsg))
				// 			})
				// 			// #endif
				// 		})
				// 		.catch(errMsg => reject(errMsg))
				// })
				return wxpay(data)
					.then(async (res) => {
						// #ifndef H5
						Promise.resolve(res)
						// #endif

						// #ifdef H5
						this.$on('h5_payment', () => {
							this.queryPayResult().then(result => {
								result ? Promise.resolve(res) : Promise.reject(res)
							}).catch(errMsg => Promise.reject(errMsg))
						})
						// #endif
					})
					.catch(errMsg => Promise.reject(errMsg))
			},

			// 支付宝支付
			handleAlipayPay(data) {
				return new Promise((resolve, reject) => {
					alipay(data)
						.then(async (res) => {
							// #ifndef H5
							resolve(res)
							// #endif

							// #ifdef H5
							this.$on('h5_payment', () => {
								this.queryPayResult().then(result => {
									result ? resolve(res) : reject(res)
								}).catch(errMsg => reject(errMsg))
							})
							// #endif
						})
						.catch(errMsg => reject(errMsg))
				})
			},
			handleKingdeeAlipayPay() {
				this.queryPayResult().then(result => {
					result ? this.handlePayResult(PaymentStatusEnum['SUCCESS']) : this.handlePayResult(
						PaymentStatusEnum['FAIL'])
				}).catch(errMsg => this.handlePayResult(errMsg))
			},

			// 钱包余额支付
			handleWalletPay() {
				return new Promise((resolve, reject) => {
					resolve(this.$zhTran('支付成功'))
				})
			},
			handleTtPay(data) {
				return new Promise((resolve, reject) => {
					ttpay(data)
						.then(async (res) => {
							resolve(res)
						})
						.catch(errMsg => reject(errMsg))
				})
			},

			// 通联支付支付
			handleTongLianPay(data) {
				return new Promise((resolve, reject) => {
					tonglianpay(data)
						.then(async (res) => {
							// #ifndef H5
							resolve(res)
							// #endif

							// #ifdef H5
							this.$on('h5_payment', () => {
								this.queryPayResult().then(result => {
									result ? resolve(res) : reject(res)
								}).catch(errMsg => reject(errMsg))
							})
							// #endif
						})
						.catch(errMsg => reject(errMsg))
				})
			},

			// E易收支付支付
			handleEEasyPay(data) {
				return new Promise((resolve, reject) => {
					eeasypay(data)
						.then(async (res) => {
							// #ifndef H5
							resolve(res)
							// #endif

							// #ifdef H5
							this.$on('h5_payment', () => {
								this.queryPayResult().then(result => {
									result ? resolve(res) : reject(res)
								}).catch(errMsg => reject(errMsg))
							})
							// #endif
						})
						.catch(errMsg => reject(errMsg))
				})
			},

			// 厚联支付支付
			handleHouLianPay(data) {
				return new Promise((resolve, reject) => {
					houlianpay(data)
						.then(async (res) => {
							// #ifndef H5
							resolve(res)
							// #endif

							// #ifdef H5
							this.$on('h5_payment', () => {
								this.queryPayResult().then(result => {
									result ? resolve(res) : reject(res)
								}).catch(errMsg => reject(errMsg))
							})
							// #endif
						})
						.catch(errMsg => reject(errMsg))
				})
			},
			// 处理结果
			handlePayResult(result) {
				if (this.pay_openid != '') {
					this.handlePayResultOther({
						result,
						order_id: this.order_id,
					})
				} else {
					uni.$emit('duringPayment', {
						result,
						payway: this.payway,
						order_id: this.order_id,
					})
				}
			},
			// 支付结果处理
			handlePayResultOther({
				result,
				order_id
			}) {
				
				switch (result) {
					case PaymentStatusEnum['SUCCESS']:
					case PaymentStatusEnum['FAIL']:
						this.$Router.replace({
							// path: '/bundle2/pages/payment_result/payment_result',
							path: '/bundle4/pages/transactres/paymentres',
							query: {
								order_id,
								from: 'order'
							}
						})
						break
					case PaymentStatusEnum['CLOSE']:
						this.$Router.push({
							path: '/bundle4/pages/transactres/paymentres',
							query: {
								order_id,
								from: 'order'
							}
						})
						break
				}
			},

			// 查询支付结果
			queryPayResult() {
				if (this.loadingPay) return
				this.loadingPay = true
				return new Promise((resolve, reject) => {
					apiPayStatus({
							from: this.from,
							order_id: this.order_id,
						}).then(({
							pay_status
						}) => {
							resolve(pay_status == 1 ? true : false)
						}).catch(errMsg => reject(errMsg))
						.finally(() => {
							this.loadingPay = false
						})
				})
			},
			oaAutoPay() {
				// H5微信登录
				const {
					code
				} = this.$Route.query;
				console.log('code', code)
				this.isWeixin = isWeixinClient();
				if (code) {
					// 带有code => 登录
					return this.oaPay(code);
				} else {
					console.log('isWeixin', this.isWeixin)
					if (this.isWeixin) {
						// 开启自动授权登录
						wechath5.getWxUrl(1);
					}
				}
			},
			async oaPay(code) {
				if (!code) return;
				const data = await wechath5.authApay(code);
				this.pay_openid = data.openid
			},
		},

		async onLoad() {
			const options = this.$Route.query
			this.from = options.from
			this.order_id = options.order_id
			this.code = options.code || ''
			// 初始化页面参数
			if (this.$Route.meta.atitle) {
				uni.setNavigationBarTitle({
					title: this.$zhTran(this.$Route.meta.atitle)
				})
			}

			try {
				if (!this.from && !this.order_id) throw this.$zhTran('页面参数有误')
				await this.queryPayResult().then(result => {
					if (result) throw this.$zhTran('订单已支付')
				})
				// #ifdef H5
				this.oaAutoPay();
				// #endif
				await this.initPageData()
				this.loadingSkeleton = false
			} catch (errMsg) {
				this.pageErrorMsg = errMsg
				this.pageStatus = PageStatusEnum['ERROR']
			}
		},

		onShow() {
			// #ifdef H5
			this.$emit('h5_payment')
			// #endif

			// #ifndef H5
			let options = wx.getEnterOptionsSync();
			if (options.scene == '1038' && options.referrerInfo.appId == this.pay_appid) {
				// 代表从收银台小程序返回
				let extraData = options.referrerInfo.extraData;
				if (!extraData) {
					// "当前通过物理按键返回，未接收到返参，建议自行查询交易结果";
					this.queryPayResult().then(result => {
						result ? this.handlePayResult(PaymentStatusEnum['SUCCESS']) : this.handlePayResult(
							PaymentStatusEnum['FAIL'])
					}).catch(errMsg => this.handlePayResult(errMsg))
				} else {
					if (extraData.code == 'success' || extraData.code == 0) {
						// "支付成功";
						this.handlePayResult(PaymentStatusEnum['SUCCESS'])
					} else if (extraData.code == 'cancel') {
						// "支付已取消";
						this.handlePayResult(PaymentStatusEnum['FAIL'])
						console.log('PAYMENT_ERROR_MSG:', errMsg)
					} else {
						// "支付失败：" + extraData.errmsg;
						this.handlePayResult(extraData.errmsg)
						console.log('PAYMENT_ERROR_MSG:', extraData.errmsg)
					}
				}
			}
			// #endif
		},

		onUnload() {
			this.handlePayResult(PaymentStatusEnum['CLOSE'])
		},
	}
</script>


<style lang="scss" scoped>
	.payment {
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		height: 100vh;
		max-height: 100vh;
		padding-bottom: calc(100rpx + 20rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(100rpx + 20rpx + env(safe-area-inset-bottom));

		&-header {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			height: 300rpx;
			@include background_linear(260deg) color: #FFFFFF;
		}


		&-main {
			flex: 1;
			margin-top: -40rpx;
			padding: 0 20rpx;
			overflow: hidden;
		}


		&-footer {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			display: flex;
			align-items: center;
			height: calc(100rpx + constant(safe-area-inset-bottom));
			height: calc(100rpx + env(safe-area-inset-bottom));
			padding: 0 20rpx constant(safe-area-inset-bottom) 20rpx;
			padding: 0 20rpx env(safe-area-inset-bottom) 20rpx;
			background-color: #FFFFFF;
		}

		.payway-container {
			padding: 0 20rpx;
			border-radius: 7px;
			background-color: #FFFFFF;

			.payway-empty {
				display: flex;
				justify-content: center;
				padding: 20rpx 0;
				font-size: $-font-size-sm;
				color: $-color-muted;
			}
		}

		.payway {
			width: 100%;

			&-item {
				width: 100%;
				display: flex;
				align-items: center;
				height: 120rpx;

				&:nth-child(n+2) {
					border-top: $-dashed-border;
				}

				&-content {
					flex: 1;
					display: flex;
					flex-direction: column;
					margin-left: 16rpx;

					&-name {
						font-size: $-font-size-nr;
						color: $-color-black;
					}

					&-tips {
						font-size: $-font-size-xxs;
						color: $-color-muted;
					}
				}
			}
		}

		&-count-down {
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 7rpx 25rpx;
			border-radius: 60px;
			margin-top: 10rpx;
			font-size: $-font-size-xxs;
			background-color: #FFFFFF;
			color: $-color-normal;
		}

		&-submit {
			flex: 1;
			position: relative;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 74rpx;
			font-size: $-font-size-nr;
			border-radius: 60px;
			@include background_linear(260deg) color: #FFFFFF;

			&--disabled::before {
				position: absolute;
				top: 0;
				bottom: 0;
				left: 0;
				right: 0;
				height: 100%;
				display: block;
				content: "";
				background: rgba(255, 255, 255, .3) !important;
			}
		}
	}
</style>